import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_wisave/CentrePage/Device/DeviceData.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'QualityItem.dart';
import 'OxidationItem.dart';
import 'SteelView.dart';
import 'package:flutter_wisave/Tools/NetworkService.dart';
import 'package:flutter_wisave/CentrePage/Class/QualityClass.dart';
import 'package:flutter_wisave/Common/TimeSwitching.dart';
import '../../Tools/ToolsLocalStorage.dart';
import '../../widgets/AppColors.dart';

class QualityPage extends StatefulWidget {
  final int initialIndex;

  const QualityPage({
    super.key,
    this.initialIndex = 0,
  });

  @override
  State<QualityPage> createState() => _QualityPageState();
}

class _QualityPageState extends State<QualityPage>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  bool breakdown = true;
  final NetworkService _networkService = NetworkService();
  late String qualityListCount = '0';

  ///脱碳
  DateTime _currentDayDateTime = DateTime.now();
  late String currentDayDate;
  List<dynamic> qualityList = [];
  List<dynamic> lostListData = [];
  List<dynamic> lostListAvgData = [];

  ///温度跟踪
  Future<void> _loadData() async {
    try {
      final result = await _fetchData();
      if (result['code'] == 200 && result['rows'] != null) {
        setState(() {
          // qualityList = List<QualityClass>.from(
          // result['rows'].map((item) => QualityClass.fromJson(item)));
          qualityList = (result['rows'] as List)
              .map((item) => (item as Map<String, dynamic>))
              .toList();
        });
      }
    } catch (e) {
      print('Error in _loadData: $e');
    }
    try {
      final result = await _fetchCountData();
      if (result['code'] == 200) {
        setState(() {
          qualityListCount = result['data'].toString();
        });
      }
    } catch (e) {
      print('Error in _loadData: $e');
    }
  }

  Future<Map<String, dynamic>> _fetchData() async {
    final deptID = await LocalStorage.getstr('deptId');
    try {
      final response = await _networkService.get(
          '/plcTimer/billettemptracking/getBilletIdList?companyId=$deptID');
      if (response.statusCode == 200) {
        return response.data;
      } else {
        throw Exception('billettemptracking Failed to load data');
      }
    } catch (e) {
      print('billettemptracking Error in _fetchData: $e');
      rethrow;
    }
  }

  Future<Map<String, dynamic>> _fetchCountData() async {
    final deptID = await LocalStorage.getstr('deptId');
    try {
      final response = await _networkService.get(
          '/plcTimer/billetdischargehistory/getBilletQuantity?companyId=$deptID');
      if (response.statusCode == 200) {
        return response.data;
      } else {
        throw Exception('steeloutday Failed to load data');
      }
    } catch (e) {
      print('steeloutday Error in _fetchData: $e');
      rethrow;
    }
  }

  ////氧化脱碳
  void _onDayDateChanged(DateTime newDate) {
    setState(() {
      _currentDayDateTime = newDate;
      currentDayDate = _formatDate(_currentDayDateTime);
      _oxidationlossData();
    });
  }

  String _formatDate(DateTime date) {
    return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
  }

  //氧化脱碳班组效率查询
  Future<void> _oxidationlossData() async {
    try {
      final result = await _fetchOxidationlossData();
      if (result['code'] == 200 && result['rows'] != null) {
        setState(() {
          lostListData = (result['rows'] as List)
              .map((item) => (item as Map<String, dynamic>))
              .toList();
        });
      }
    } catch (e) {
      print('Error in _loadData: $e');
    }

    //氧化脱碳平均效率查询
    try {
      final result = await _fetchOxidationlossAvgInfoData();
      if (result['code'] == 200 && result['rows'] != null) {
        setState(() {
          lostListAvgData = (result['rows'] as List)
              .map((item) => (item as Map<String, dynamic>))
              .toList();
        });
      }
    } catch (e) {
      print('Error in _loadData: $e');
    }
  }

  Future<Map<String, dynamic>> _fetchOxidationlossData() async {
    final deptID = await LocalStorage.getstr('deptId');
    try {
      final response = await _networkService
          .get('/plcTimer/oxidationloss/listInfo?companyId=$deptID');
      if (response.statusCode == 200) {
        return response.data;
      } else {
        throw Exception('oxidationloss/listInfo Failed to load data');
      }
    } catch (e) {
      print('oxidationloss/listInfo Error in _fetchData: $e');
      rethrow;
    }
  }

  //氧化脱碳平均效率查询
  Future<Map<String, dynamic>> _fetchOxidationlossAvgInfoData() async {
    final deptID = await LocalStorage.getstr('deptId');
    try {
      final response = await _networkService
          .get('/plcTimer/oxidationloss/avgInfo?companyId=$deptID');
      if (response.statusCode == 200) {
        return response.data;
      } else {
        throw Exception('oxidationloss/avgInfo Failed to load data');
      }
    } catch (e) {
      print('oxidationloss/avgInfo Error in _fetchData: $e');
      rethrow;
    }
  }

  //生命周期函数：当组件初始化的时候就会触发
  //输入inits可快速生成该方法
  @override
  void initState() {
    super.initState();
    _tabController = TabController(
      length: 3,
      vsync: this,
      initialIndex: widget.initialIndex,
    );
    _loadData();
    _oxidationlossData();
  }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent, // 状态栏颜色
    ));
    // 获取屏幕的宽度和高度
    final mediaQuery = MediaQuery.of(context);
    final screenWidth = mediaQuery.size.width;
    final screenHeight = mediaQuery.size.height;
    bool breakdown = true;

    return Scaffold(
      backgroundColor: AppColors.backgroundColor,
      appBar: AppBar(
        title: const Text('质量管理'),
        foregroundColor: AppColors.textPrimary,
        centerTitle: true,
        backgroundColor: Colors.transparent, // Make AppBar transparent
        flexibleSpace: Container(
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/images/home/home_topbg.png'),
              fit: BoxFit.cover,
            ),
          ),
        ),
        bottom: PreferredSize(
          preferredSize: const Size.fromHeight(48), // Adjust height as needed
          child: Container(
            decoration: const BoxDecoration(
              color: Colors.transparent, // Set the background color
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(20),
                topRight: Radius.circular(20),
              ),
            ),
            child: TabBar(
              isScrollable: false,
              indicatorColor: Colors.blue,
              indicatorWeight: 2,
              indicatorPadding: const EdgeInsets.only(right: 50, left: 50),
              indicatorSize: TabBarIndicatorSize.tab,
              labelColor: TDTheme.of(context).grayColor12,
              unselectedLabelColor: TDTheme.of(context).grayColor8,
              labelStyle:
                  const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
              unselectedLabelStyle: const TextStyle(fontSize: 16),
              controller: _tabController,
              tabs: [
                Tab(
                    child: Text("钢坯温度跟踪",
                        style: TextStyle(color: AppColors.textPrimary))),
                Tab(
                    child: Text("氧化与脱碳",
                        style: TextStyle(color: AppColors.textPrimary))),
                Tab(
                    child: Text("钢坯查询",
                        style: TextStyle(color: AppColors.textPrimary))),
              ],
            ),
          ),
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: [
          ListView(
            children: [
              const SizedBox(height: 20),
              Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Row(
                    mainAxisSize: MainAxisSize.max,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      ..._buttonWithQType(
                          '炉内钢坯总数', screenWidth, qualityListCount),
                      const SizedBox(width: 10),
                      ..._buttonWithQType('运行方向', screenWidth, 'UP'),
                    ],
                  ),
                  const SizedBox(height: 20),
                  SizedBox(
                    height: screenHeight - 280,
                    child: ListView.builder(
                      itemCount: qualityList.length,
                      itemBuilder: (context, index) {
                        return QualityItem(quality: qualityList[index]);
                      },
                    ),
                  ),
                ],
              ),
            ],
          ),
          ListView(
            children: [
              const SizedBox(height: 20),
              Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Row(
                    mainAxisSize: MainAxisSize.max,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      ..._buttonWithType(
                          '每日数据', screenWidth, !this.breakdown, 0, () {
                        setState(() {
                          this.breakdown = false;
                        });
                      }),
                      const SizedBox(width: 10),
                      ..._buttonWithType('每月数据', screenWidth, this.breakdown, 0,
                          () {
                        setState(() {
                          this.breakdown = true;
                        });
                      }),
                    ],
                  ),
                  Padding(
                    padding: const EdgeInsets.all(15.0),
                    child: Container(
                      padding: const EdgeInsets.all(16.0),
                      decoration: BoxDecoration(
                        color: AppColors.cardColor,
                        borderRadius: BorderRadius.circular(8.0),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.grey.withOpacity(0.2),
                            blurRadius: 6.0,
                          ),
                        ],
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          TimeSwitching(
                            mode: this.breakdown
                                ? SwitchingMode.month
                                : SwitchingMode.day,
                            onDateChanged: _onDayDateChanged,
                          ),
                          const SizedBox(height: 10), // Add some space
                          Padding(
                            padding: const EdgeInsets.all(10.0),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Expanded(
                                  child: Text(
                                    '班组',
                                    textAlign: TextAlign.left,
                                    style: TextStyle(
                                        fontWeight: FontWeight.bold,
                                        color: AppColors.textPrimary),
                                  ),
                                ),
                                Expanded(
                                  child: Text(
                                    '氧化烧损率',
                                    textAlign: TextAlign.left,
                                    style: TextStyle(
                                        fontWeight: FontWeight.bold,
                                        color: AppColors.textPrimary),
                                  ),
                                ),
                                Expanded(
                                  child: Text(
                                    '脱碳百分比',
                                    textAlign: TextAlign.right,
                                    style: TextStyle(
                                        fontWeight: FontWeight.bold,
                                        color: AppColors.textPrimary),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          ListView.builder(
                            shrinkWrap: true,
                            physics: const NeverScrollableScrollPhysics(),
                            itemCount: lostListData.length,
                            itemBuilder: (context, index) {
                              return OxidationItem(data: lostListData[index]);
                            },
                          ),
                        ],
                      ),
                    ),
                  ),
                  Padding(
                    padding:
                        const EdgeInsets.only(top: 10, left: 15, right: 15),
                    child: Container(
                      padding: EdgeInsets.all(16.0),
                      decoration: BoxDecoration(
                        color: AppColors.cardColor,
                        borderRadius: BorderRadius.circular(8.0),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.grey.withOpacity(0.2),
                            blurRadius: 6.0,
                          ),
                        ],
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            '各班各组平均值',
                            style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.bold,
                                color: AppColors.textPrimary),
                          ),
                          const SizedBox(height: 16.0),
                          Row(
                              mainAxisSize: MainAxisSize.max,
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                ..._meanWithType(
                                    0,
                                    lostListAvgData.isNotEmpty
                                        ? '${lostListAvgData[0]['burningLoss']}%'
                                        : '0%',
                                    screenWidth),
                                ..._meanWithType(
                                    1,
                                    lostListAvgData.isNotEmpty
                                        ? '${lostListAvgData[0]['decarburation']}%'
                                        : '0%',
                                    screenWidth),
                              ]),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
          ListView(
            children: const [SteelView()],
          ),
        ],
      ),
    );
  }
}

List<Widget> _meanWithType(num type, String content, double screenWidth) {
  return [
    Container(
      margin: EdgeInsets.only(left: type == 1 ? 18.0 : 0), // 设置间距
      height: 84, // 调整背景图的高度
      width: screenWidth / 2 - 50,
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage(AppColors.isDarkMode
              ? 'assets/images/centre/production_bg${type + 1}_b.png'
              : 'assets/images/centre/production_bg${type + 1}.png'), // 替换为你的图片路径
          fit: BoxFit.cover,
        ),
        borderRadius: BorderRadius.circular(8.0),
      ),
      child: Stack(
        children: [
          Positioned(
            bottom: 10,
            width: screenWidth / 2 - 50,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  type == 0 ? '氧化烧损率' : '脱碳百分比)',
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    color: AppColors.textPrimary,
                    fontSize: 14,
                  ),
                ),
                Text(
                  content,
                  textAlign: TextAlign.center,
                  style: TextStyle(
                      color: type == 0 ? Color(0xFF2AB6F7) : Color(0xFF814FF3),
                      fontSize: 30,
                      fontWeight: FontWeight.bold),
                ),
              ],
            ),
          ),
        ],
      ),
    ),
  ];
}

List<Widget> _buttonWithType(String title, double screenWidth, bool select,
    int tabIndex, VoidCallback onTap) {
  String imgBg = AppColors.isDarkMode
      ? 'assets/images/cloud/cloud_gray_b.png'
      : 'assets/images/cloud/cloud_gray.png';
  String imgIcon = 'assets/images/cloud/icon_gray.png';
  if (select) {
    imgBg = AppColors.isDarkMode
        ? 'assets/images/cloud/cloud_blue_b.png'
        : 'assets/images/cloud/cloud_blue.png';
    if (title == '每日数据') {
      imgIcon = 'assets/images/cloud/icon_week.png';
    } else {
      imgIcon = 'assets/images/cloud/icon_month.png';
    }
  } else {
    imgBg = AppColors.isDarkMode
        ? 'assets/images/cloud/cloud_gray_b.png'
        : 'assets/images/cloud/cloud_gray.png';
    if (title == '每日数据') {
      imgIcon = 'assets/images/cloud/icon_week_un.png';
    } else {
      imgIcon = 'assets/images/cloud/icon_month_un.png';
    }
  }

  return [
    GestureDetector(
      onTap: onTap,
      child: Container(
        height: 50,
        width: (screenWidth - 50) / 2,
        decoration: BoxDecoration(
          // color: AppColors.cardColor, // Add white background
          image: DecorationImage(
            image: AssetImage(imgBg),
            fit: BoxFit.cover,
          ),
          borderRadius: BorderRadius.circular(8.0),
        ),
        child: Stack(
          children: [
            Positioned.fill(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  const SizedBox(
                      width: 8), // Add some space between image and text
                  Image.asset(
                    imgIcon, // Replace with your image path
                    width: 30, // Adjust size as needed
                    height: 30,
                  ),
                  const SizedBox(
                      width: 12), // Add some space between image and text
                  Text(
                    title,
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      color: AppColors.textPrimary,
                      fontSize: 14,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    ),
  ];
}

List<Widget> _buttonWithQType(
    String title, double screenWidth, String content) {
  String imgBg = AppColors.isDarkMode
      ? 'assets/images/centre/icon_quality_count_b.png'
      : 'assets/images/centre/icon_quality_count.png';
  if (title == '运行方向') {
    imgBg = AppColors.isDarkMode
        ? 'assets/images/centre/icon_quality_up_b.png'
        : 'assets/images/centre/icon_quality_up.png';
  }
  return [
    GestureDetector(
      child: Container(
        height: 66,
        width: (screenWidth - 50) / 2,
        decoration: BoxDecoration(
          color: AppColors.cardColor, // Add white background
          image: DecorationImage(
            image: AssetImage(imgBg),
            fit: BoxFit.cover,
          ),
          borderRadius: BorderRadius.circular(8.0),
        ),
        child: Stack(
          children: [
            Positioned.fill(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  // const SizedBox(
                  //     width: 12), // Add some space between image and text
                  Text(
                    title,
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      color: AppColors.textPrimary,
                      fontSize: 14,
                    ),
                  ),
                  const SizedBox(height: 15),
                  Text(
                    content,
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      color: AppColors.textPrimary,
                      fontSize: 14,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    ),
  ];
}
